﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MN.Framework.Common
{
    public abstract class BaseContext : DbContext
    {
        private static BaseContext _context;
        private static string _connectionstring;

        protected BaseContext(string conectionstring)
            : base(conectionstring)
        {
            _context = this;
            _connectionstring = conectionstring;
        }
        public override int SaveChanges()
        {

            if (this.ChangeTracker.HasChanges())
            {
                this.ChangeTracker.DetectChanges();
                var entries = this.ChangeTracker.Entries();
                //Dictionary<string, int> lastRecnos = new Dictionary<string, int>();
                foreach (var entry in entries)
                {
                    if (entry.State == EntityState.Modified || entry.State == EntityState.Added)
                    {
                        var entity = entry.Entity as BaseEntity;
                        if (!entity.Validate())
                        {
                            var errors = entity.GetErrorMessages();
                            errors=errors.Insert(0, "شناسه " + entity.ID + " \n");
                            throw new Exception(errors);
                        }
                    }
                }

                return base.SaveChanges();
            }//end if has changed entity
            return 0;

        }
        public static BaseContext GetContext()
        {
            return _context;
        }
        public static string GetConnectionString()
        {
            return _connectionstring;
        }      
    }
}
